package cn.turboinfo.dongying.api.domain.admin.usecase.activity;

import cn.turboinfo.dongying.api.domain.common.service.activity.ActivityService;
import cn.turboinfo.dongying.api.domain.common.service.file.FileAttachmentService;
import cn.turboinfo.dongying.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.dongying.api.domain.web.component.file.FileRefTypeConstant;
import cn.turboinfo.dongying.api.entity.common.enumeration.activity.ActivityAuditStatus;
import cn.turboinfo.dongying.api.entity.common.enumeration.user.UserType;
import cn.turboinfo.dongying.api.entity.common.pojo.activity.Activity;
import cn.turboinfo.dongying.api.entity.common.pojo.activity.ActivityUpdater;
import cn.turboinfo.dongying.api.entity.common.pojo.file.FileAttachment;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.base.enums.EnableStatus;
import net.sunshow.toolkit.core.qbean.helper.component.request.QBeanUpdaterHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class ActivityUpdateUseCase extends AbstractUseCase<ActivityUpdateUseCase.InputData, ActivityUpdateUseCase.OutputData> {
    private final ActivityService activityService;

    private final FileAttachmentService fileAttachmentService;

    @Override
    protected OutputData doAction(InputData inputData) {

        Long id = inputData.getId();
        Long shopId = inputData.getShopId() == null ? 0L : inputData.getShopId();

        Activity activity = activityService.getByIdEnsure(id);

        if (!Objects.equals(activity.getShopId(), shopId)) {
            throw new RuntimeException("活动不属于该商户");
        }

        if (activity.getAuditStatus().equals(ActivityAuditStatus.PASS)) {
            throw new RuntimeException("活动已通过审核，不可修改");
        }

        ActivityUpdater.Builder builder = ActivityUpdater.builder(id);

        QBeanUpdaterHelper.copyPropertiesToUpdateBuilder(builder, ActivityUpdater.class, inputData);

        if (inputData.getDescription() == null) {
            builder.withDescription(StringUtils.EMPTY);
        }

        if (inputData.getOrganizer() == null) {
            builder.withOrganizer(StringUtils.EMPTY);
        }

        if (inputData.getLocation() == null) {
            builder.withLocation(StringUtils.EMPTY);
        }

        activity = activityService.update(builder.build());

        List<Long> imageIdList = inputData.getImageIdList();
        Set<Long> imageIdSet = new HashSet<>(imageIdList);

        List<FileAttachment> fileAttachmentList = fileAttachmentService.findByRefIdAndRefType(activity.getId(), FileRefTypeConstant.ACTIVITY_IMG);

        Map<Long, FileAttachment> fileAttachmentMap = fileAttachmentList
                .stream()
                .collect(Collectors.toMap(FileAttachment::getId, fileAttachment -> fileAttachment));

        // 删除需要删除的附件
        for (FileAttachment fileAttachment : fileAttachmentList) {
            if (!imageIdList.contains(fileAttachment.getId())) {
                fileAttachmentService.deleteById(fileAttachment.getId());
            }
        }

        // 更新需要更新的附件
        for (Long imageId : imageIdList) {
            if (fileAttachmentMap.containsKey(imageId)) {
                imageIdSet.remove(imageId);
            }
        }

        if (imageIdSet.size() > 0) {
            fileAttachmentService.updateRefId(imageIdSet.stream().toList(), activity.getId());
        }

        return OutputData.builder()
                .activity(activity)
                .build();
    }

    @EqualsAndHashCode(
            callSuper = true
    )
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class InputData extends AbstractUseCase.InputData {

        private Long shopId;

        @NotNull(
                message = "id不能为空"
        )
        private Long id;

        @NotBlank(
                message = "活动名称不能为空"
        )
        private String name;

        private String description;

        @NotBlank(
                message = "活动类型不能为空"
        )
        private String activityType;

        /**
         * 活动范围
         */
        private List<UserType> activityScope;

        private String organizer;

        private String location;

        /**
         * 已报名
         */
        private Integer applied;

        @NotNull(
                message = "限制数量不能为空"
        )
        private Integer limitNum;

        @NotNull(
                message = "是否开放报名不能为空"
        )
        private EnableStatus openApply;

        private LocalDateTime startTime;

        private LocalDateTime endTime;

        @NotNull(
                message = "状态不能为空"
        )
        private EnableStatus status;

        /**
         * 图片编码列表
         */
        private List<Long> imageIdList;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private Activity activity;
    }
}
